<template>
  <div class="pager-form">
    <upload-approval-sheet
      v-if="approvalType === 'upload'"
      ref="uploadSheet"
      :pager="pager"
      :queryData="queryData"
      :pointData="pointData"
      showAdviceInput
    />
    <use-car-pager
      v-if="approvalType === 'useCar'"
      ref="useCarSheet"
      :pager="pager"
      :queryData="queryData"
      :pointData="pointData"
      showAdviceInput
    />
    <office-buy-pager
      v-if="approvalType === 'officeBuy'" 
      ref="officeBuy" 
      :pager="pager"
      :queryData="queryData"
      :pointData="pointData"
      showAdviceInput
    />
    <witten
      v-if="approvalType === 'leave'"
      ref="wittenSheet"
      :pager="pager"
      :queryData="queryData"
      :pointData="pointData"
      :processCode="processCode"
      showAdviceInput
    />
    <el-row
      v-if="!isReportTask && !queryData.isTSP"
      type="flex"
      justify="center"
      style="margin-top: 30px"
    >
      <el-button
        v-if="isFormKeyContain('LZ')"
        type="primary"
        size="small"
        @click="handSaveProcess"
        >保存流转
      </el-button>
      <el-button
        v-if="isFormKeyContain('TY')"
        type="primary"
        size="small"
        @click="handSaveProcess('end_process', '同意')"
        >同意
      </el-button>
      <el-button
        v-if="isFormKeyContain('ZP')"
        type="primary"
        size="small"
        @click="showSelectUserDialog('指派')"
        >指派
      </el-button>
      <el-button
        v-if="isFormKeyContain('SPR')"
        type="primary"
        size="small"
        @click="showSelectUserDialog('指派')"
        >审批人
      </el-button>
      <el-button
        v-if="isFormKeyContain('BH')"
        size="small"
        @click="handReject"
        >驳回</el-button
      >
      <el-button
        v-if="isFormKeyContain('B_TY')"
        size="small"
        @click="handSaveProcess('end_process', '不同意')"
        >不同意</el-button
      >
      <el-button type="primary" size="small" @click="showDialogProcess"
        >流程监控
      </el-button>
    </el-row>
    <!-- 流程监控 -->
    <process-monitor
      ref="process"
      :fromTask="true"
      :showPager="false"
      :activities="activities"
      :processStatics="processStatics"
    ></process-monitor>
    <el-dialog
      :title="dialogUserTitle"
      :visible.sync="dialogSelectUser"
      width="80%"
      style="margin-top: -6vh"
    >
      <div class="radio-list" v-if="modalType !== '加签'">
        <el-radio-group v-model="handRadio">
          <el-radio
            class="media-for-groupBtn"
            v-for="(item, index) in pointNameList"
            :label="item.value"
            :key="index"
            >{{ item.name }}</el-radio
          >
        </el-radio-group>
      </div>
      <user-manager
        v-if="
          (handRadio && handRadio.indexOf('END') == -1) || modalType === '加签'
        "
        ref="userManager"
        :userOuter="hiddenOuter"
        :onSelectUsers="handSelectConsignor"
      />
      <!-- 结束确认框 -->
      <div v-else class="end_confirm">
        <div class="content">
          <i class="el-icon-warning" style="color: #e6a23c"></i>
          <span>确定要结束此流程吗？</span>
        </div>
        <div class="option">
          <el-button size="small" @click="dialogSelectUser = false"
            >取消</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="handSaveProcess('end_process')"
            >确定</el-button
          >
        </div>
      </div>
    </el-dialog>
  </div>
</template>
  
  <script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import { mapGetters } from "vuex";
import { updateHolidayApprovalTask, updateOfficeBuyApprovalTask, updateUseCarApprovalTask } from "@/api/work.js";
import { getInfo, postSendShortInfo } from '@/api/user'
import {
  getProcessPointNames,
  completeTasks,
  getProcessMinitorGraph,
  postEntrustToOther,
  postCountersign,
  getTaskProcessInfo1,
  getTaskInfoByUserIdAndTaskId,
} from "@/api/workflow.js";
import { parseTime, filterObj, previewFileAppendPath } from "@/utils/index";

export default {
  name: "PagerForm",
  components: {
    Treeselect,
    "user-manager": () =>
      import("@/views/markSys/taskCenter/components/userManager.vue"),
    "process-monitor": () =>
      import(
        "@/views/markSys/taskCenter/approve/handler/components/ProcessMinitor/index.vue"
      ),
    UploadApprovalSheet: () => import("../UploadApproval/Sheet"),
    Witten: () => import("@/views/markSys/components/Witten/index"),
    UseCarPager: () =>
      import("@/views/markSys/taskCenter/components/UserCarPager"),
    OfficeBuyPager: () => import('@/views/markSys/components/OfficeBuy/index'),
  },
  props: {
    pager: {
      type: Object,
    },
    approvalType: {
      type: String,
    },
    processCode: {
      type: String
    },
    isReportTask: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    approvalType: {
      handler(value) {
        this.loading = false;
      },
    },
    handRadio(data) {
      if (data) {
        // 选择节点对应对象
        const selectPoint = this.pointNameList.filter(
          (e) => e.value === data
        )[0];
        this.handRadioName = selectPoint.name;
      }
    },
  },
  data() {
    return {
      dialogSelectUser: false,
      isFirstAssign: false, // 是否第一次指派
      consignor: "", // 委托用户
      handRadio: "",
      handRadioName: "",
      activities: [],
      processStatics: {
        curCount: 0,
        doneCount: 0,
        willCount: 0,
      }, // 流程监控节点统计
      loading: true,
      dialogProcessVisible: false,
      modalType: null,
      lineNum: 1,
      queryData: null,
      dialogUserTitle: "选择人员", // 人员选择对话框标题
      pointNameList: [], // 流程节点名称
      pointData: {},
    };
  },
  computed: {
    ...mapGetters(["id", "name"]),
    hiddenOuter() {
      if (this.handRadioName === "领导审批") {
        return false;
      }
      return true;
    },
  },
  created() {
    this.queryData = this.$route.params;
    // 初始化发文字段信息内容
    this.requestProcessPointNames();
    this.requestCommenthi();
    this.requestProcessGraph();
    this.fetchUserInfo()
  },
  methods: {
    parseTime,
    // 跳转到在线office页面
    previewFileAppendPath,
    // 判断formKey是否包含指定值
    isFormKeyContain(value) {
      const { formKey } = this.queryData;
      if (formKey) {
        const keys = formKey.split(",") || [];
        return keys.includes(value);
      } else if (formKey == "") {
        return true;
      }
      return false;
    },
    // 获取审批意见
    getAdvice() {
      let _comment = "";
      if (this.approvalType === "upload") {
        const { comment } = this.$refs.uploadSheet;
        _comment = comment;
      } else if (this.approvalType === "useCar") {
        const { comment } = this.$refs.useCarSheet;
        _comment = comment;
      } else if (this.approvalType === "officeBuy") {
        const { comment } = this.$refs.officeBuy;
        _comment = comment;
      } else if (this.approvalType === "leave") {
        const { comment } = this.$refs.wittenSheet;
        _comment = comment;
      }
      return _comment;
    },
    // 显示选择委托人对话框
    showSelectUserDialog(type, line = 1) {
      const modalTypeTitle = {
        加签: "加签",
        指派: "转下一步",
        委托: "选择委托人员",
      };
      this.dialogUserTitle = modalTypeTitle[type];
      this.dialogSelectUser = true;
      this.modalType = type;
      this.lineNum = line;
    },
    // 处理委托
    handSelectConsignor(users) {
      if (this.handRadio.indexOf("END") === -1 && !users.length) {
        this.$message.warning("请选择处理人");
        return;
      }
      // 委托
      if (this.modalType === "委托") {
        postEntrustToOther(this.queryData.targetId, users[0].id).then((res) => {
          if (res && res.data.message === "转发任务成功") {
            this.$notify({
              title: "成功",
              message: "转发任务成功",
              type: "success",
              duration: 2000,
            });
            this.$router.push({ name: "Index" });
          } else {
            this.$message.error("无效操作，转发任务失败");
          }
          this.$refs["userManager"].clearSelect();
          this.dialogSelectUser = false;
        });
      } else if (this.modalType === "加签") {
        const { id, nodeName } = this.queryData;
        const userIds = users.map((e) => e.id.toString());
        postCountersign(id, nodeName, { adduserList: userIds }).then((res) => {
          if (res && res.data.code == "200") {
            this.$notify({
              title: "成功",
              message: "加签成功",
              type: "success",
              duration: 2000,
            });
          } else {
            this.$message.error("无效操作，加签失败");
          }
          this.$refs["userManager"].clearSelect();
          this.dialogSelectUser = false;
        });
      } else {
        // 指派
        const selectPoint = this.pointNameList.filter(
          (e) => e.value === this.handRadio
        )[0];
        const pointName = selectPoint.name;
        const userStr = users.map(item => item.first_name).join('、')
        const title = `请仔细核对流转至 <text style="color: red">${pointName} (${userStr})</text> 审批，是否确定？`

        this.$confirm(
          title,
          `温馨提示`,
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            dangerouslyUseHTMLString: true
          }
        ).then(() => {
          this.handAssign(users);
        });
      }
    },
    // 生成流转内容
    getCirculationStr(assignName) {
      if (this.handRadio.indexOf("END") === -1) {
        return "已流转至" + assignName.join(",");
      }
      return "办理完结";
    },
    // 处理指派
    handAssign(users) {
      // 判断节点
      if (!this.handRadio) {
        this.$message.warning("请选择下一步节点");
        return;
      }
      const formatUsers = users.map((e) => e.id.toString());
      const assignName = users.map((e) => e.name);
      const _comment = this.getAdvice()
      
      const paramObj = {
        dealReason: _comment || this.getCirculationStr(assignName),
        dealType: "0",
        dealUserId: this.id,
        dealUserName: this.name,
        dealUnitId: "0",
        businessKey: this.queryData.targetId,
        line: this.handRadio,
        circulationUserStr: assignName,
        userList: formatUsers,
      };
      completeTasks(this.queryData.id, paramObj).then((res) => {
        if (res && res.data.message === "完成任务成功") {
          this.$notify({
            title: "成功",
            message: "指派任务操作成功",
            type: "success",
            duration: 2000,
          });
          // 上报审批发送短信
          if(this.approvalType === 'upload') {
            this.handleSendShortInfo({type: 'dsp', users})
          }
          this.$router.push({ name: "Index" });
        } else {
          this.$notify({
            title: "失败",
            message: "指派任务操作失败",
            type: "error",
            duration: 2000,
          });
        }
      });
    },
    // 保存流程
    // type: 区分保存流转、结束流程
    // status: 请假结束流程时是否通过
    handSaveProcess(type, status) {
      if (status) {
        this.approvalType === "useCar" && (this.$refs.useCarSheet.comment = status);
        this.approvalType === "officeBuy" && (this.$refs.officeBuy.comment = status);
        this.approvalType === "leave" && (this.$refs.wittenSheet.comment = status);
      }
      const _comment = this.getAdvice();
      if (!_comment) {
        this.$message.warning("请填写审批意见");
        return;
      }
      let param = {
        dealReason: _comment || " ",
        pubPagerWord: "",
        pubPagerDate: "",
        dealType: "0",
        dealUserId: this.id,
        dealUserName: this.name,
        dealUnitId: "0",
        businessKey: this.queryData.targetId,
        line: "SP001",
      };
      // 如果结束流程
      if (type === "end_process") {
        param.line = "END999";
        param.userList = [];
      }
      param = filterObj(param);
      completeTasks(this.queryData.id, param).then(async (res) => {
        if (res && res.data.message === "完成任务成功") {
          this.$notify({
            title: "成功",
            message: "保存流转成功",
            type: "success",
            duration: 2000,
          });
          // 如果请假审批结束流程，修改审批状态
          if (type === "end_process") {
            if(this.approvalType === "leave") {
              await updateHolidayApprovalTask(this.queryData.targetId, {
                sp_status: status || "同意"
              })
            } else if(this.approvalType === "officeBuy") {
              await updateOfficeBuyApprovalTask(this.queryData.targetId, {
                sp_status: status || "同意",
            });
            } else if(this.approvalType === "useCar") {
              await updateUseCarApprovalTask(this.queryData.targetId, {
                sp_status: status || "同意",
              });
            }
          } 
          // 上报审批发送短信
          if(this.approvalType === 'upload') {
            this.handleSendShortInfo({type: 'result', users: [this.userInfo]})
          }
          this.$router.push({ name: "Index" });
        } else {
          this.$notify({
            title: "失败",
            message: "保存流转失败",
            type: "error",
            duration: 2000,
          });
        }
      });
    },
    // 驳回
    handReject() {
      const _comment = this.getAdvice();
      if (!_comment) {
        this.$message.warning("请填写审批意见");
        return;
      }
      const param = {
        dealReason: _comment,
        dealType: "1",
        dealUserId: this.id,
        dealUserName: this.name,
        dealUnitId: "",
        rejectElemKey: this.queryData.rejectKey,
      };
      completeTasks(this.queryData.id, param).then((res) => {
        if (res && res.data) {
          this.$notify({
            title: "成功",
            message: "驳回审批成功",
            type: "success",
            duration: 2000,
          });
          this.$router.push({ name: "Index" });
        } else {
          this.$notify({
            title: "失败",
            message: "驳回审批失败",
            type: "error",
            duration: 2000,
          });
        }
      });
    },
    async handleSendShortInfo({type, users}) {
      console.log(users);
      // 检查手机号码是否有效
      const phoneReg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
      const phones = users.filter(user => phoneReg.test(user.phone)).map(user => user.phone)
      if(!phones.length) return
      await postSendShortInfo({
        type,
        phone: phones,
      })
    },
    // 显示流程监控页面
    showDialogProcess() {
      this.requestProcessMinitor();
      this.$refs.process.dialogProcessVisible = true;
    },
    // 获取流程高亮图
    requestProcessGraph() {
      const { proInsId, proDefId } = this.queryData;
      if (proInsId && proDefId) {
        getProcessMinitorGraph({
          proDefid: proDefId,
          proInsid: proInsId,
        }).then((res) => {});
      }
    },
    // 获取流程监控数据
    requestProcessMinitor() {
      // let result = []
      // Object.keys(this.pointData).forEach(
      //   key =>{
      //     let point = this.pointData[key]
      //     if(point.length){
      //       point.forEach(
      //         e =>{
      //           e.name = key
      //         }
      //       )
      //       result = result.concat(point)
      //     }
      //   }
      // )
      // this.activities = result
      getTaskProcessInfo1(this.pager.id).then((res) => {
        const { curCount, doneCount, willCount, data, proDefKey } =
          (res.data && res.data.data) || {};
        this.activities = data;
        this.processStatics = {
          modelName: proDefKey,
          curCount: curCount,
          doneCount: doneCount,
          willCount: willCount,
        };
      });
      // getProcessMinitor(this.queryData.proId).then(
      //   res => {
      //     const data = res.data
      //     data.forEach(
      //       e => {
      //         e._startTime = parseTime(e.startTime, '{y}-{m}-{d}')
      //         e._endTime = parseTime(e.endTime, '{y}-{m}-{d}')
      //       }
      //     )
      //   }
      // )
    },
    // 获取流程节点名称
    requestProcessPointNames() {
      const { id } = this.queryData;
      getProcessPointNames(id).then((res) => {
        const list = res.data.data;
        let data = [];
        if (!list.length) return;
        list.forEach((e) => {
          if (Object.keys(e).length && Object.values(e)[0]) {
            data.push({ name: Object.values(e)[0], value: Object.keys(e)[0] });
          }
        });
        this.pointNameList = data;
        this.handRadio = data[0].value;
      });
    },
    // 遍历所有用户
    getUsersList(data, result) {
      data.forEach((item) => {
        // result = [...result, ...item.user_department]
        item.user_department.forEach((user) => {
          result.push(user);
        });
        if (item.child && item.child.length > 0) {
          this.getUsersList(item.child, result);
        }
      });
      return result;
    },
    // 获取审批记录
    requestCommenthi() {
      const { targetId } = this.queryData;
      if (targetId) {
        // getCommentPro(proInsId, proDefId).then(res => {
        //   this.pointData = res.data.data;
        // });
        getTaskInfoByUserIdAndTaskId({
          userId: this.id,
          bussKey: targetId,
        }).then((res) => {
          const { comment } = res.data.data;
          this.pointData = comment;
        });
      }
    },
    async fetchUserInfo() {
      const { startUserId } = this.queryData
      const { data } = await getInfo(startUserId)
      this.userInfo = data
    },
  },
};
</script>
  <style media="printContent">
@page {
  size: auto;
  /* auto is the initial value */
  margin: 10mm 15mm 0;
}
</style>
  <style lang="scss">
.pager-form {
  margin-bottom: 20px;
  overflow-x: hidden;
  .radio-list {
    padding: 0 20px 12px;
    text-align: center;
    @media screen and (max-width: 500px) {
      .el-radio {
        margin: 10px 5px;
      }
    }
    .el-radio {
      margin-right: 15px;
      .el-radio__inner {
        display: none;
      }
      .el-radio__label {
        font-size: 16px;
        color: #b5b5b5;
        border: 1px solid;
        padding: 5px 10px;
        border-radius: 13px;
      }
      .el-radio__input.is-checked + .el-radio__label {
        color: #fff;
        background: #409eff;
      }
    }
  }
}
.end_confirm {
  width: 308px;
  margin: 78px auto 10px;
  padding: 16px 20px;
  vertical-align: middle;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  font-size: 16px;
  box-shadow: 0 2px 12px 0 #e0e0e0;
  .content {
    margin-bottom: 20px;
  }
  .option {
    text-align: right;
  }
}
.input-warpper {
  max-width: 800px;
  width: 100%;
  margin: 10px auto;

  .name {
    width: 80px;
    color: #797979;
    line-height: 30px;
  }
}

.el-divider--horizontal {
  margin: 24px auto;
}
.el-button + .el-button {
  margin-left: 10px;
}
.el-dialog__body {
  padding: 20px;
}
</style>
  